package cn.nn200433.mqtt.core;

import cn.hutool.core.lang.Assert;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.server.HttpServerRequest;
import cn.hutool.json.JSONUtil;
import cn.nn200433.mqtt.core.emqx.dto.AuthDTO;
import cn.nn200433.mqtt.service.IEMQXAuthService;
import lombok.extern.slf4j.Slf4j;

/**
 * http服务器（emqx认证用）
 *
 * @author nn200433
 * @date 2022-08-09 009 20:17:19
 */
@Slf4j
public class HttpServer {

    private HttpServer() {
    }

    /**
     * http服务器
     *
     * @param port            港口
     * @param mqttAuthService mqtt身份验证服务
     * @return
     * @author nn200433
     */
    public HttpServer(Integer port, IEMQXAuthService mqttAuthService) {
        HttpUtil.createServer(port)
                .addAction("/mqtt/auth", (req, res) -> {
                    try {
                        Boolean match = mqttAuthService.verify(buildAuth(req));
                        Assert.isTrue(match, "认证失败");
                        res.sendOk();
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                        res.sendError(HttpStatus.HTTP_UNAUTHORIZED, e.getMessage());
                    }
                }).start();
    }

    /**
     * 构建身份验证
     *
     * @param request 请求
     * @return {@link AuthDTO }
     * @author nn200433
     */
    private AuthDTO buildAuth(HttpServerRequest request) {
        return JSONUtil.toBean(request.getBody(), AuthDTO.class);
    }

}
